package org.xlp.base.application.util;

import org.xlp.utils.io.XLPIOUtil;

import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

/**
 * Description: 读取文件中RSA的公钥或私钥工具类
 * <br/>date: 2024/11/14 16:54
 *
 * @version 1.0
 * @author: xlp
 */
public class RSAFileReaderUtils {
    /**
     * 私钥文件名称
     */
    public static final String PRIVATE_KEY_FILE_NAME = "privateKey.pem";

    /**
     * 公钥文件名称
     */
    public static final String PUBLIC_KEY_FILE_NAME = "publicKey.dat";

    /**
     * 私钥缓存，防止每次重新加载
     */
    private  static PrivateKey privateKey;

    /**
     * 公钥缓存，防止每次重新加载
     */
    private static PublicKey publicKey;

    /**
     * 从私钥文件读取私钥对象
     * @return 私钥对象
     * @throws Exception 假如读取失败，则抛出该异常
     */
    public static PrivateKey getPrivateKey() throws Exception {
        if (privateKey != null) return privateKey;
        InputStream in = RSAFileReaderUtils.class.getClassLoader().getResourceAsStream(PRIVATE_KEY_FILE_NAME);
        byte[] bytes = XLPIOUtil.IOToByteArray(in, true);
        privateKey = RSAUtils.loadPrivateKey(bytes);
        return privateKey;
    }

    /**
     * 从私钥文件读取私钥对象
     * @return 私钥对象
     * @throws Exception 假如读取失败，则抛出该异常
     */
    public static PublicKey getPublicKey() throws Exception {
        if (publicKey != null) return publicKey;
        InputStream in = RSAFileReaderUtils.class.getClassLoader().getResourceAsStream(PUBLIC_KEY_FILE_NAME);
        byte[] bytes = XLPIOUtil.IOToByteArray(in, true);
        publicKey = RSAUtils.loadPublicKey(bytes);
        return publicKey;
    }

    /**
     * 从私钥文件读取私钥对象，并通过base64转换成字符串返回
     * @return 私钥对象
     * @throws Exception 假如读取失败，则抛出该异常
     */
    public static String getStrPublicKey() throws Exception {
        PublicKey publicKey = getPublicKey();
        return Base64.getEncoder().encodeToString(publicKey.getEncoded());
    }
}
